//
//  HomeParLeaveListController.m
//  ChatDemo-UI2.0
//
//  Created by syun on 16/8/15.
//  Copyright © 2016年 syun. All rights reserved.
//

#import "HomeParLeaveListController.h"
#import "HomeLeaveCell.h"
#import "HomeParLeaveDetailController.h"
#import "HomeparLeaveModel.h"
#import "SYHomeParLeaveViewController.h"

@interface HomeParLeaveListController ()<UITableViewDelegate,UITableViewDataSource,reloadDataDelegate>
{
    UIView *noworkView;
    int lPageNum;
    BOOL leaRefresh;
    EmptyStateView *emptyView;//空状态
    EmptyStateView *noWifiView;//无网络状态
}
@property (nonatomic, strong) UITableView *table;
@property (nonatomic, strong) NSMutableArray *dataArray;
@end

@implementation HomeParLeaveListController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self configNav];
    [self requestLeaveData];
//    [self initNoworkView];
    // Do any additional setup after loading the view.
}
-(NSMutableArray *)dataArray
{
    if (_dataArray==nil) {
        _dataArray=[NSMutableArray array];
    }
    return _dataArray;
}
-(UITableView *)table
{
    if (_table==nil) {
        _table=[[UITableView alloc]initWithFrame:CGRectMake(0, SafeAreaTopHeight, SCREENWIDTH, SCREENHEIGH - SafeAreaTopHeight - SafeAreaBottomHeight) style:UITableViewStylePlain];
        _table.delegate=self;
        _table.dataSource=self;
        _table.showsVerticalScrollIndicator = NO;
        _table.separatorStyle=UITableViewCellSeparatorStyleNone;
    }
    return _table;
}

- (void)configNav {
    
   self.navBar.nav_titleLabel.text=@"请假";
   
   
   self.navBar.rightButton.hidden = NO;
   self.navBar.rightImg.hidden = NO;
   self.navBar.rightImg.image = [UIImage imageNamed:@"add_"];
   
//    UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    addBtn.frame = CGRectMake(0, 0, 44, 44);
//    self.navBar.rightButton.imageEdgeInsets = UIEdgeInsetsMake(0, 22, 0,0);
    [self.navBar.rightButton addTarget:self action:@selector(addLaeav:) forControlEvents:UIControlEventTouchUpInside];
//    [addBtn setImage:[UIImage imageNamed:@"add_"] forState:UIControlStateNormal];
   
   
//    UIBarButtonItem *addBarBtnItem = [[UIBarButtonItem alloc] initWithCustomView:addBtn];
//    self.navBar.navigationItem.rightBarButtonItem = addBarBtnItem;

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requestLeaveData) name:@"requestLeaveData" object:nil];
    
    self.table.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [self requestLeaveData];
    }];
    
    self.table.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        [self requestMoreLeaveData];
    }];
    
    [self.view addSubview:self.table];
    
    emptyView = [[EmptyStateView alloc] initWithFrame:CGRectMake(0, (SCREENHEIGH-110)/2-70, SCREENWIDTH, 110) andBackImage:@"myfriend_empty" andBottomStr:@"您的孩子很健康，暂无请假记录"];
    [self.table addSubview:emptyView];
    
    
    noWifiView = [[EmptyStateView alloc] initNoWifiWithFrame:CGRectMake(0, (SCREENHEIGH-64-175)/2, SCREENWIDTH, 175) andBackImage:@"noWifi" andBottomStr:@"网络出错啦,点击重新加载"];
    noWifiView.userInteractionEnabled= YES;
    noWifiView.delegate = self;
    [self.view addSubview:noWifiView];
    
}
- (void)requestLeaveData
{
    BaseModel *param = [BaseModel param];
    param.method = @"api_leave_bystudent";
    param.pageno = @"1";
    param.pagesize = @"20";
//    NSUserDefaults *ud=[NSUserDefaults standardUserDefaults];
//    NSString *studentID=[ud objectForKey:@"studentID"];
    param.studentid = @"0";
    
    [self.dataArray removeAllObjects];
    
    [Utils get:nil parameters:param.mj_keyValues success:^(NSInteger recode, id jsonObject) {
        
        NSArray *arr = [jsonObject objectForKey:@"re_data"];
        if (arr.count==0) {
            
            [self ->_table reloadData];
            self ->_table.tableFooterView = [[UIView alloc] init];
            [self ->_table.mj_header endRefreshing];
            [self->noWifiView hideEmptyImage];
            [self->emptyView showEmptyImage];
            return;
            
        }else if (arr.count==20)
        {
            self ->leaRefresh = YES;
        }else{
            self ->leaRefresh = NO;
        }
//        self->noworkView.hidden=YES;
        [self->emptyView hideEmptyImage];
        
        self->lPageNum = 2;
        
        for (NSDictionary *dic in arr) {
            HomeparLeaveModel* model=[HomeparLeaveModel mj_objectWithKeyValues:dic];
            [self.dataArray addObject:model];
            
        }
        
        [self->_table reloadData];
        [self ->_table.mj_header endRefreshing];
        [self->_table.mj_footer endRefreshing];
    } failure:^(NSInteger recode, NSError *error) {
        
        if (error.code == -1009) {
            self.table.hidden = YES;
            [self.table.mj_header endRefreshing];
            [self->emptyView hideEmptyImage];
            [self->noWifiView showEmptyImage];
        }
    }];

}
- (void)requestMoreLeaveData
{
    BaseModel *param = [BaseModel param];
    param.method = @"api_leave_bystudent";
    param.pageno = [NSString stringWithFormat:@"%d",lPageNum];;
    param.pagesize = @"20";
    [Utils get:nil parameters:param.mj_keyValues success:^(NSInteger recode, id jsonObject) {
        
        NSArray *arr = [jsonObject objectForKey:@"re_data"];
        if (arr.count == 20) {
            
            self ->lPageNum++;
            self ->leaRefresh = YES;
            
        }else{
            
            self ->leaRefresh = NO;
        }
        
        
        for (NSDictionary *dic in arr) {
            HomeparLeaveModel* model=[HomeparLeaveModel mj_objectWithKeyValues:dic];
            [self.dataArray addObject:model];
            
        }
        
        [self->_table reloadData];
        
        [self->_table.mj_footer endRefreshing];
        
    } failure:^(NSInteger recode, NSError *error) {
        
        if (error.code == -1009) {
            self.table.hidden = YES;
            [self.table.mj_footer endRefreshing];
            [self->emptyView hideEmptyImage];
            [self->noWifiView showEmptyImage];
        }

    }];
}

- (void)reloadCurrentData
{
    self.table.hidden = NO;
    [noWifiView hideEmptyImage];
    [self requestLeaveData];
}

- (void)addLaeav:(UIButton *)sender
{
    
    SYHomeParLeaveViewController *leaveVC = [[SYHomeParLeaveViewController alloc] init];
    
    //HomeParLeaveController *leaveVC=[[HomeParLeaveController alloc]init];
    
    [self.navigationController pushViewController:leaveVC animated:YES];
    
}
#pragma mark -UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataArray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return 62;
    
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    HomeLeaveCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"HomeLeaveCell" owner:nil options:nil]  objectAtIndex:0];
    }
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    UIView *line=[[UIView alloc]initWithFrame:CGRectMake(0, 61.5, SCREENWIDTH, 0.5)];
    line.backgroundColor=RGBACOLOR(199, 199, 204, 1);
    [cell.contentView addSubview:line];
    
    HomeparLeaveModel *leaveModel=[self.dataArray objectAtIndex:indexPath.row];
    
    cell.leaveTitle.text=[NSString stringWithFormat:@"%@的请假申请",leaveModel.studentname];
    cell.leaveClass.text=leaveModel.classname;
    
    NSString *jointime=[Utils getDataStringWithoutSecondString:leaveModel.jointime];

    cell.leaveTime.text=jointime;
    
    
    if (leaveModel.studentlogo.length>0) {
        if (![leaveModel.studentlogo hasPrefix:@"http"]) {
            NSString * logo = [REQUESTIMAGEURL stringByAppendingString:leaveModel.studentlogo];
            [cell.headImage sd_setImageWithURL:[NSURL URLWithString:logo]];
        }
    }else
    {
        cell.headImage.image=[UIImage imageNamed:@"logo_01"];
    }
    
    
    int logotype=(int)leaveModel.studentlogotype;
    NSString *nameStr=leaveModel.studentname;
    if (logotype==0) {
        cell.headName.hidden=YES;
        if (leaveModel.studentname.length>2) {
            nameStr = [nameStr substringFromIndex:nameStr.length-2];
            cell.headName.text=nameStr;
        }else
        {
            cell.headName.text=nameStr;
        }
    }else
    {
       cell.headName.hidden=YES;
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    HomeParLeaveDetailController *detailVC=[[HomeParLeaveDetailController alloc]init];
    detailVC.lmodel=[self.dataArray objectAtIndex:indexPath.row];
    [self.navigationController pushViewController:detailVC animated:YES];
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
        
        if (leaRefresh == NO) {
            
            UIView *view =[[ UIView alloc] initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, 60)];
            UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, 0.4)];
            lineView.backgroundColor = RGBACOLOR(222, 223, 229, 1);
            //                [view addSubview:lineView];
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0.4, VIEW_WIDTH, 59.6)];
            label.text = @"没有更多内容了";
            label.textAlignment = NSTextAlignmentCenter;
            label.font = [UIFont boldSystemFontOfSize:14];
            label.textColor = [UIColor colorWithHexString:@"979797"];
            [view addSubview:label];
            self.table.tableFooterView = view;
            
            self.table.mj_footer = nil;
        }else if (leaRefresh == YES){
            
            self.table.tableFooterView = nil;
            self.table.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
                
                [self requestMoreLeaveData];
            }];
        }
        
    }
}

-(void)initNoworkView{
    
    noworkView = [[UIView alloc] initWithFrame:CGRectMake(0,64, SCREENWIDTH, SCREENHEIGH - 64)];
    noworkView.backgroundColor = [UIColor clearColor];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn sizeToFit];
    btn.frame = CGRectMake(0, 0, SCREENWIDTH, noworkView.frame.size.height);
    
    [btn setImage:[UIImage imageNamed:@"leave_class_no_"] forState:UIControlStateNormal];
    
    btn.enabled = NO;
    
    [noworkView addSubview:btn];
    
    noworkView.hidden = YES;
    
    [self.view addSubview:noworkView];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
